package com.css.check;

import com.css.utils.SourceConfigureUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadStaticPaper {

    private static Logger logger = Logger.getLogger(ReadStaticPaper.class);

    /*public static void main(String args[]){
        readHttpToDocument("localhost:8080");
    }*/

    public static void readHttpToDocument(String ipAndPort) {
        SourceConfigureUtils utils = SourceConfigureUtils.getInstance();
        String staticPaperPath = utils.getStaticPaperPath();
        List<String> titlePositionList = utils.getTitlePositionList();
        List<String> titleList = utils.getTitleList();

        Document doc = null;
        try {
            // 获取静态文件
            doc = Jsoup.connect("http://" + ipAndPort + staticPaperPath)
                    .data("query", "Java")
                    .cookie("auth", "token")
                    .timeout(8000)
                    .post();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (doc == null){
            logger.error("服务器" + ipAndPort + "请求静态试卷返回Document对象为空指针");
            return;
        }

        // 存储不匹配的题目
        List<String> unMatchTitles = new ArrayList<String>();

        Elements content = doc.getElementsByClass("topicContent");

        if (!content.isEmpty()){
            Elements titles = new Elements();
            for (Element element : content){
                titles.addAll(element.getElementsByClass("question_title"));
            }

            for (int i = 0; i < titles.size(); i++){
                for (int j = 0; j < titlePositionList.size(); j++){
                    int position = Integer.parseInt(titlePositionList.get(j));
                    // 需要校验的题目序号
                    if ((position - 1) == i){
                        String title = titleList.get(j);
                        if (!title.equals(titles.get(i).text())){
                            unMatchTitles.add(title);
                        }
                    }
                }
            }

            if (unMatchTitles.size() == titlePositionList.size()){
                logger.error("服务器" + ipAndPort + ", 获取得到的题目与设置的规则完全不匹配");
            } else{
                logger.debug("服务器" + ipAndPort + ", 获取得到的题目与设置的规则完全匹配");
            }
        }else{
            // 白屏问题
            logger.error("服务器" + ipAndPort + "请求静态试卷没有题目内容");
        }
    }
}
